<!--  -->
<template>
  <div style="padding-top:100px">
    <div class="app-title-container title-position">
      <modules-title titleName="稳定性方案详情">
        <template slot="btn">
          <el-button class="filter-item" plain="" size="mini" @click="handleBack">返回
          </el-button>
          <el-button type="primary" size="mini"
            v-if="ruleForm.stability_status == 1 || ruleForm.stability_status == -1"
            @click="handlEdit()">编辑
          </el-button>

          <el-button type="primary" size="mini"
            v-if="ruleForm.stability_status == 1 || ruleForm.stability_status == -1 "
            @click="handlSubmit()">
            <span v-if="ruleForm.stability_scheme_type != 2">提交审批</span>
            <span v-else>提交变更审批</span>
          </el-button>

          <el-button type="primary" size="mini"
            v-if="ruleForm.stability_status === 3 && (ruleForm.creator_id === userInfo ||  ruleForm.project_leader_id === userInfo) "
            @click="handlChange">
            方案变更
          </el-button>
          <el-button type="primary" size="mini"
                     v-if="ruleForm.stability_status === 3 && (ruleForm.creator_id === userInfo ||  ruleForm.project_leader_id === userInfo) "
                     @click="handlPrint(ruleForm)">
            打印
          </el-button>
          <el-button type="primary" size="mini" @click="handlUndo" v-if="ruleForm.scheme_check &&
              ruleForm.scheme_check.Cancelable && boole">
            撤销
          </el-button>
          <el-button type="danger" size="mini"
            v-if="ruleForm.stability_status == 1 || ruleForm.stability_status == -1"
            @click="handlDeletet()">
            删除
          </el-button>
        </template>
      </modules-title>
    </div>
    <div style="padding:20px">
      <el-row :gutter="20">
        <el-col :span="18">
          <el-tabs type="border-card" class="box">
            <el-tab-pane label="稳定性方案明细">
              <plan :plan-data="ruleForm" :sample-list="sampleList" :checl-samp="checlSamp"
                :conditions-inve="conditionsInve"></plan>
            </el-tab-pane>
            <el-tab-pane label="检测项目表明细">
              <check :check-data="checkData" :stability='ruleForm.stability_scheme_type'
                :check-list="checkList"></check>
            </el-tab-pane>
            <el-tab-pane label="稳定性试验放样信息">
              <experiment :check-data="checkData" :experiment="experiment"></experiment>
            </el-tab-pane>
          </el-tabs>
        </el-col>

        <el-col :span="6">
          <div class="title-container">
            <div class="left">
              <div class="title-con"><span>当前版本</span></div>
            </div>
          </div>
          <div class="title-container">{{ruleForm.version_no}}</div>

          <div class="title-container" style="margin-top:10px">
            <div class="left">
              <div class="title-con"><span>操作人</span></div>
            </div>
          </div>

          <div class="title-container" style="justify-content: space-between;">
            <div>{{ruleForm.creator_name}}</div>
            <div>{{ruleForm.created_at}}</div>
            <div>创建人</div>
          </div>

          <div class="title-container" style="justify-content: space-between"
            v-if="ruleForm.stability_status > 2">
            <div>{{ruleForm.auditor}}</div>
            <div>{{ruleForm.updated_at}}</div>
            <div>审批人</div>
          </div>

          <template v-if="ruleForm.stability_status == 3">
            <div class="title-container" style="margin-top:10px">
              <div class="left">
                <div class="title-con"><span>变更记录</span></div>
              </div>
            </div>
            <div v-for="(item,index) in ruleForm.change_log" :key="index"
              style="margin-bottom:10px">
              <template v-if="item !== null && item.version_no !==''">
                <ul>
                  <li>{{item.version_no}}</li>
                  <li>{{item.created_at}}</li>
                  <li>
                    <el-button type="text" @click="toDetails(item.id)">查看详情</el-button>
                  </li>
                </ul>
                <div>{{item.change_reason}}</div>
              </template>
            </div>
          </template>

        </el-col>
      </el-row>
    </div>
    <!--对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body
      :before-close="cancel" :close-on-click-modal="false" v-if="open">
      <el-form ref="formOpen" :model="formOpen" :rules="rules" label-width="120px" size="small">
        <el-form-item label="审批结论" prop="stability_status">
          <el-radio-group v-model="formOpen.stability_status">
            <el-radio :label="3">通过</el-radio>
            <el-radio :label="-1">回退修改</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审批意见" prop="idea">
          <el-input v-model="formOpen.idea" type="textarea" placeholder="请输入审批意见" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button plain size="small" @click="cancel">取 消</el-button>
        <el-button size="small" type="primary" @click="submitForm">
          确定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="变更说明" :visible.sync="openChange" width="600px" append-to-body
      :before-close="cancelChange" :close-on-click-modal="false" v-if="openChange">
      <el-form :model="openChangeForm" ref="openChangeForm" label-width="100px">
        <el-form-item label="变更原因" prop="change_reason"
          :rules="[{ required: true, message: '请填写变更原因', trigger: 'blur' }]">
          <el-input type="textarea" v-model="openChangeForm.change_reason"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button plain size="small" @click="cancelChange">取 消
        </el-button>
        <el-button size="small" type="primary" @click="submitChange">
          确 定
        </el-button>
      </div>
    </el-dialog>

    <!-- 打印稳定性方案 -->
    <vue-easy-print ref="printLookInfo">
      <template slot-scope="func">
        <div id="print">
          <plan-print :data="data"/>
        </div>
      </template>
    </vue-easy-print>

  </div>
</template>

<script>
import {
  stabilityEditor,
  approval,
  stabilityDetail,
  subApproval,
  staDelete,
  submitChange
} from "@/api/stability/giveUp";
import planPrint from '@/views/stability/giveUp/print/index'
export default {
  components: {
    plan: () => import("../../components/plan.vue"),
    check: () => import("../../components/check.vue"),
    experiment: () => import("../../components/experiment.vue"),
    planPrint
  },
  data() {
    return {
      ruleForm: {
        scheme_check: {},
        version_no: ""
      },
      checkData: null,
      checkList: [],
      experiment: [],
      sampleList: [],
      checlSamp: [],
      conditionsInve: [],
      open: false,
      title: "",
      formOpen: {
        stability_status: undefined,
        idea: "",
        id: ""
      },
      rules: {
        stability_status: [
          { required: true, message: "请选择审批结论", trigger: "change" }
        ],
        idea: [{ required: true, message: "请输入审批意见", trigger: "blur" }]
      },
      sss: "",
      openChange: false,
      openChangeForm: {
        id: "",
        change_reason: ""
      },
      boole: false,
      userInfo: null,
      data:{}
    };
  },
  //是计算属性，也可以理解为一个方法。
  computed: {},
  //属性是手动定义的所需监听的值
  watch: {},
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.userInfo = this.$store.getters.userInfo.user.id;
    if (this.$route.query.id) {
      this.handlEditor();
    }
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {},
  //是Vue实例对象上绑定的方法，供当前Vue组件作用域内使用，
  methods: {
    //获取编辑数据
    handlEditor() {
      stabilityEditor(this.$route.query.id).then(res => {
        if (res.code === 200) {
          this.ruleForm = res.data || {};
          if (
            this.ruleForm.scheme_check &&
            this.ruleForm.scheme_check.check_creator_id == this.userInfo
          ) {
            this.boole = true;
          }
          if (res.data.stability_table_info !== "") {
            this.checkData = JSON.parse(res.data.stability_table_info) || {};
          }
          if (res.data.stability_plan !== "") {
            this.experiment = JSON.parse(res.data.stability_plan) || [];
          }
          this.checkList = res.data.stability_details || [];
          this.sampleList = res.data.sample_list || [];
          this.sampleList.forEach(item => {
            this.checlSamp.push(item.id);
          });
          this.conditionsInve = res.data.stability_details || [];
          if (this.conditionsInve && this.conditionsInve.length > 0) {
            this.sss = this.conditionsInve[0].name;
          }
        }
      });
    },

    //返回
    handleBack() {
      this.$route.params.refresh = true;
      this.$router.go(-1);
    },

    //审批
    handlApproval() {
      this.open = true;
      this.title = "审批流程";
      this.formOpen.id = this.$route.query.id;
    },

    //编辑
    handlEdit() {
      this.$router.push({
        path: "/stability/giveUp/created",
        query: { id: this.$route.query.id, type: 1 }
      });
    },

    //删除
    handlDeletet() {
      this.$confirm("确认删除吗？")
        .then(_ => {
          staDelete(this.$route.query.id).then(res => {
            if (res.code === 200) {
              this.$route.params.refresh = true;
              this.$router.go(-1);
            }
          });
        })
        .catch(_ => {});
    },

    handlSubmit() {
      let ssss = this.handlTree(this.ruleForm);
      if (ssss.boole) {
        this.$message.error(ssss.msg);
        return;
      }
      // if (this.ruleForm.stability_instrument_infos.length === 0) {
      //   this.$message.error("请至少选择一个稳定性仪器");
      //   return;
      // }
      if (this.ruleForm.stability_table_info === "") {
        this.$message.error("检查项目表明细表为空");
        return;
      }
      if (this.ruleForm.stability_plan === "") {
        this.$message.error("稳定性试验放样信息表为空");
        return;
      }
      let aaa = JSON.parse(this.ruleForm.stability_table_info) || {};
      let bbb = JSON.parse(this.ruleForm.stability_plan) || [];
      let ccc = this.handlTableCharm(aaa);
      if (!ccc) return;
      let ddd = this.handlStableCharm(bbb);
      if (!ddd) return;
      if (this.ruleForm.stability_scheme_type == 2) {
        this.openChange = true;
      } else {
        subApproval(this.$route.query.id).then(res => {
          if (res.code === 200) {
            this.$message.success("提交成功");
            this.handlEditor();
          }
        });
      }
    },

    //变更审核取消
    cancelChange() {
      this.openChangeForm = {
        id: "",
        change_reason: ""
      };
      this.openChange = false;
    },

    //变更审核提交
    submitChange() {
      this.$refs.openChangeForm.validate(valid => {
        if (valid) {
          this.openChangeForm.id = this.$route.query.id;
          submitChange(this.openChangeForm).then(res => {
            if (res.code === 200) {
              this.$message.success("提交变更审批成功");
              this.$route.params.refresh = true;
              this.$router.push("/stability/giveUp");
              this.cancelChange();
            } else {
              this.$message.error(res.msg);
            }
          });
        } else {
          return false;
        }
      });
    },

    //验证tree
    handlTree(row) {
      var boole, msg;
      if (row.sample_list == null) {
        msg = "请添加样品";
        boole = true;
        return { boole: boole, msg: msg };
      }
      if (row.sample_list.length === 0) {
        msg = "请添加样品";
        boole = true;
        return { boole: boole, msg: msg };
      } else {
        let aaa = row.stability_details;
        if (aaa.length === 0) {
          msg = "请勾选样品";
          boole = true;
          return { boole: boole, msg: msg };
        } else {
          for (let i = 0; i < aaa.length; i++) {
            let bbb = aaa[i].conditions;
            if (bbb.length === 0) {
              msg = `请勾选${aaa[i].label}的考察类型`;
              boole = true;
              return { boole: boole, msg: msg };
            } else {
              for (let j = 0; j < bbb.length; j++) {
                if (bbb[j].conditions.length === 0) {
                  msg = `请勾选${bbb[j].label}的放置条件`;
                  boole = true;
                  return { boole: boole, msg: msg };
                }
              }
            }
          }
        }
      }
      return { boole: false };
    },

    //方案变更
    handlChange() {
      this.$router.push({
        path: "/stability/giveUp/created",
        query: { id: this.$route.query.id, type: 2 }
      });
    },

    //打印
    handlPrint(row) {
      this.data = row
      setTimeout(() => {
        this.$refs.printLookInfo.print()
      }, 200)
    },

    //取消
    cancel() {
      this.open = false;
      this.formOpen = {
        stability_status: undefined,
        idea: "",
        id: ""
      };
    },

    //审批确定
    submitForm() {
      this.$refs.formOpen.validate(valid => {
        if (valid) {
          approval(this.formOpen).then(res => {
            if (res.code === 200) {
              this.$message.success("提交成功");
              this.cancel();
            }
          });
        } else {
          return false;
        }
      });
    },

    //查看详情
    toDetails(id) {
      let newQuery = { id: id };
      this.$router.replace({
        query: newQuery
      });
      location.reload();
    },

    //效验检查项目表明细
    handlTableCharm(val) {
      let aa, bb, cc, dd;
      for (let key in val) {
        let dic = {};
        aa = key.split("?");
        let index = this.ruleForm.stability_details.findIndex(
          a => a.stability_sample_info.id == aa[0]
        );
        if (index !== -1) {
          bb = this.ruleForm.stability_details[index].label;
          let index1 = this.ruleForm.stability_details[
            index
          ].inspect_types.findIndex(a => a.inspect_type.id == aa[1]);
          if (index1 !== -1) {
            cc = this.ruleForm.stability_details[index].inspect_types[index1]
              .inspect_type.inspect_type_name;
            dd = bb + cc + "未勾选取样点";
          }
        }
        for (let i = 0; i < val[key].tableData.length; i++) {
          if (i !== val[key].tableData.length - 1) {
            let sss = val[key].tableData[i];
            let bo = false;
            for (let obj in sss) {
              if (obj !== "name" && obj !== "num" && obj !== "boole") {
                let obj1 = obj.split("-")[0];
                if (
                  val[key].headList === null ||
                  val[key].headList.length === 0
                ) {
                  bo = true;
                } else {
                  let zzz = val[key].headList.findIndex(a => a == obj1);
                  if (zzz !== -1) {
                    if (typeof sss[obj] != "string") {
                      if (!dic[obj] && typeof dic[obj] != "bool") {
                        dic[obj] = false;
                      }
                      if (sss[obj]) {
                        bo = true;
                        dic[obj] = true;
                        continue;
                      }
                    }
                  }
                }
              }
            }
            if (!bo) {
              this.$message.error(dd);
              return false;
            }
          }
        }
        for (let a in dic) {
          if (!dic[a]) {
            this.$message.error(dd);
            return false;
          }
        }
      }
      return true;
    },

    //效验稳定性试验放样信息
    handlStableCharm(val) {
      for (let i = 0; i < val.length; i++) {
        let obj = val[i];
        for (let key in obj) {
          if (key.indexOf("使用倍数") != -1) {
            let sss = key.split("-");
            if (sss.length > 1 && obj[sss[1]] !== 0) {
              if (obj[key] == 0 || obj[key] == undefined) {
                this.$message.error("样品统计使用倍数不能为0");
                return false;
              }
            }
          }
        }
      }
      return true;
    },
    // 撤销
    handlUndo() {
      const subdata = {
        flow_id: this.ruleForm.scheme_check.id,
        model_type: "StabilityScheme"
      };
      this.$comFun
        .cancelFunc(subdata)
        .then(() => {
          this.$message({
            type: "success",
            message: "已撤销"
          });
          this.handlEditor();
        })
        .catch(err => {
          this.$message.error(err);
        });
    }
  }
};
</script>
<style scoped lang="scss">
@import "@/styles/variables.scss";
.title-container {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  font-size: 14px;
  height: 30px;
  .left {
    width: 100px;
    .title-con {
      font-size: 16px;
      color: $main-color;
      padding-left: $block-space-x;
      border-left: 2px solid $main-color;
    }
  }
  .right {
    width: 300px;
    padding-left: 30px;
    display: flex;
    box-sizing: border-box;
    justify-content: space-between !important;
  }
}
ul {
  padding: 0;
  margin: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* @import url(); 引入css类 */
::v-deep .el-card__body {
  padding: 20px 0;
}
.box {
  height: 850px;
  overflow-y: auto !important;
  color: #000;
  font-size: 16px;
}
::v-deep .box::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::v-deep .box::-webkit-scrollbar-thumb {
  border-radius: 100px;
  background: #cccccc;
}

::v-deep .box::-webkit-scrollbar-track {
  border-radius: 0;
  background: rgba(0, 0, 0, 0.1);
}
</style>
